<template>
  <div class="xtx-pagination">
    <a
      href="javascript:"
      @click="currentPage = currentPage - 1"
      v-if="currentPage > 1"
      >上一页</a
    >
    <span v-if="pageInfo.start > 1">...</span>
    <a
      @click="currentPage = item"
      href="javascript:"
      :class="{ active: item === currentPage }"
      v-for="item in pageInfo.pageButtons"
      :key="item"
      >{{ item }}</a
    >
    <span v-if="pageInfo.end < pageInfo.pageTotal">...</span>
    <a
      href="javascript:"
      @click="currentPage = currentPage + 1"
      v-if="currentPage < pageInfo.pageTotal"
      >下一页</a
    >
  </div>
</template>
<script>
import { computed } from "vue";
import { useVModel } from "@vueuse/core";
export default {
  name: "XtxPagination",
  props: {
    page: {
      type: Number,
      default: 1,
    },
    pageCount: {
      type: Number,
      default: 0,
    },
    pageSize: {
      type: Number,
      default: 5,
    },
  },
  setup(props, { emit }) {
    const currentPage = useVModel(props, "page", emit);
    // 定义数据总数
    const totalCount = computed(() => props.pageCount);
    // 每页数据条数
    const pageSize = computed(() => props.pageSize);

    // 页面中显示页码个数
    let pageButtonNumber = 5;
    // 偏移量 = 页面中页码个数 / 2 向下取整
    let pageOffset = Math.floor(pageButtonNumber / 2);
    // 页码计算,页码限制需要通过计算属性返回
    const pageInfo = computed(() => {
      // 开始页码  =  当前页码 - 页码偏移量
      let start = currentPage.value - pageOffset;
      // 结束页码
      let end = start + pageButtonNumber - 1;

      // 计算总页数 = 数据总数 / 每页显示数据 向上取整
      const pageTotal = Math.ceil(totalCount.value / pageSize.value);
      // 判断极值;
      // 开始页小于一
      if (start < 1) {
        // 开始值设置为一
        start = 1;
        // 当开始值改变,结束值需要重新计算
        let temp = start + pageButtonNumber - 1;
        end = temp > pageTotal ? pageTotal : temp;
      }
      if (end > pageTotal) {
        end = pageTotal;
        let temp = end - pageButtonNumber + 1;
        start = temp < 1 ? 1 : temp;
      }
      // 定义分页数组
      let pageButtons = [];
      for (let i = start; i <= end; i++) {
        pageButtons.push(i);
      }
      return {
        start,
        end,
        pageButtons,
        pageTotal,
      };
    });
    return {
      pageInfo,
      currentPage,
    };
  },
};
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333;
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>
